package cn.dapeng.designPatterns.singleton;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * DCL:双重检测
 * 锁的粒度小，效率更高
 */
public class LazySingleton_02 {
    private volatile static LazySingleton_02 instance;

    private LazySingleton_02() {
    }

    public static LazySingleton_02 getInstance() {
        if (instance == null) {
            synchronized (LazySingleton_02.class) {
                if (instance == null) {
                    instance = new LazySingleton_02();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        Set<Integer> set = new CopyOnWriteArraySet<>();
        int testTimes = 10_0000;

        for (int i = 0; i < testTimes; i++) {
            new Thread(() -> {
                set.add(LazySingleton_02.getInstance().hashCode());
            }).start();
        }

        System.out.println("size:: " + set.size());
    }
}
